package pl.mchaniewski.ryneczek.web.user;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.services.PortfolioService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.web.FormButton;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class ChangePortfolioNameBean extends FormButton {
    private PortfolioService portfolioService;
    private SelectedPortfolioBean selectedPortfolioBean;
    private PortfolioListBean portfolioListBean;

    /* Form */
    @Size(min = 1, max = 20, message = "{newportfoliobean.namesize}")
    private String name;

    @Autowired
    public void setPortfolioService(PortfolioService portfolioService) {
        this.portfolioService = portfolioService;
    }

    @Autowired
    public void setSelectedPortfolioBean(
            SelectedPortfolioBean selectedPortfolioBean) {
        this.selectedPortfolioBean = selectedPortfolioBean;
    }

    @Autowired
    public void setPortfolioListBean(PortfolioListBean portfolioListBean) {
        this.portfolioListBean = portfolioListBean;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @PostConstruct
    public void preInit() {
        if (selectedPortfolioBean.getSelectedPortfolioId() == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_INDEX);
        }
    }

    public String save() {
        if (portfolioService.changeName(
                selectedPortfolioBean.getSelectedPortfolioId(), getName()) != null) {
            portfolioListBean.init();

            FacesMessageUtil.addMessage(getButton(), I18nUtil
                    .getLocalizedMessage("changeportfolionamebean.success"),
                    FacesMessage.SEVERITY_INFO);
        } else {
            FacesMessageUtil.addMessage(getButton(), I18nUtil
                    .getLocalizedMessage("changeportfolionamebean.notSuccess"),
                    FacesMessage.SEVERITY_WARN);
        }

        return NavigationUtil.SAME_PAGE;
    }

}
